package bizsocket.sample.j2se.common;

import bizsocket.core.AbstractSerialContext;
import bizsocket.core.RequestContext;
import bizsocket.core.RequestQueue;
import bizsocket.core.SerialSignal;
import bizsocket.sample.j2se.LoggerUtil;
import bizsocket.tcp.Packet;
import bizsocket.tcp.PacketFactory;
import bizsocket.tcp.Request;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by tong on 16/9/27.
 */
public class OrderListSerialContext extends AbstractSerialContext {
    private static final String TAG = OrderListSerialContext.class.getSimpleName();

    private SamplePacket orderListPacket;
    private int[] orderIdArr;
    private int[] orderQuerySeqArr;

    private Map<Integer, Packet> orderTypeHashMap = new ConcurrentHashMap<>();

    public OrderListSerialContext(SerialSignal serialSignal, RequestContext requestContext) {
        super(serialSignal, requestContext);
    }

    @Override
    public String getRequestPacketId() {
        String packetId = getRequestContext().getRequestPacket().getPacketID();
        return packetId;
    }

    @Override
    public boolean shouldProcess(RequestQueue requestQueue, Packet packet) {
        boolean result = super.shouldProcess(requestQueue, packet);
        if (!result) {
            return false;
        }

        SamplePacket responsePacket = (SamplePacket) packet;

        JSONObject obj = null;
        try {
            obj = new JSONObject(responsePacket.getContent());
        } catch (JSONException e) {
            e.fillInStackTrace();
        }
        if (packet.getCommand() == SampleCmd.QUERY_ORDER_LIST.getValue()) {
            if (!SampleProtocolUtil.isSuccessResponsePacket(responsePacket)) {
                return false;
            }
            //订单列表信息
            JSONArray resultArr = obj.optJSONArray("result");

//            PacketFactory packetFactory = requestQueue.getBizSocket().getPacketFactory();
            if (resultArr.length() == 0) {
                return false;
            }

            orderListPacket = (SamplePacket) packet;
            orderIdArr = new int[resultArr.length()];
            orderQuerySeqArr = new int[resultArr.length()];
            for (int i = 0; i < resultArr.length(); i++) {
                JSONObject order = resultArr.optJSONObject(i);
                if (order == null) {
                    continue;
                }

                int orderId = order.optInt("orderId", -1);
                if (orderId == -1) {
                    continue;
                }

                orderIdArr[i] = orderId;
                //发起查询订单类型的查询
                SamplePacket samplePacket = buildQueryOrderTypePacket(requestQueue, orderId);
                if (null != samplePacket && null != orderQuerySeqArr) {
                    String packetID = samplePacket.getPacketID();
                    if (null != packetID) {
                        orderQuerySeqArr[i] = Integer.parseInt(packetID);
                        LoggerUtil.i("同步请求订单类型: " + samplePacket.getContent());
                        requestQueue.getBizSocket().getSocketConnection().sendPacket(samplePacket);
                    }
                }
            }
        } else if (packet.getCommand() == SampleCmd.QUERY_ORDER_TYPE.getValue()) {
            if(orderTypeHashMap != null) {
                SamplePacket samplePacket = (SamplePacket) packet;

                if (samplePacket.getPacketID() != null) {
                    boolean contain = false;
                    try {
                        int orderid = obj.optInt("orderId");
                        for (int i = 0; i < orderIdArr.length; i++) {
                            if (orderid == orderIdArr[i] && Integer.parseInt(samplePacket.getPacketID()) == orderQuerySeqArr[i]) {
                                contain = true;
                                orderTypeHashMap.put(orderid, packet);
                                break;
                            }
                        }

                    } catch (Exception e) {
                        e.fillInStackTrace();
                    }
                    if (!contain) {
                        return false;
                    }
                }
            }

        }
        return true;
    }

    private SamplePacket buildQueryOrderTypePacket(RequestQueue requestQueue, int orderId) {
        JSONObject params = new JSONObject();
        try {
            params.put("orderId", String.valueOf(orderId));
        } catch (JSONException e) {
            e.fillInStackTrace();
        }
        if (null != requestQueue && null != requestQueue.getBizSocket() && null != requestQueue.getBizSocket().getPacketFactory() && null != params && null != (SamplePacket) requestQueue.getBizSocket().getPacketFactory().getRequestPacket(new Request.Builder().command(SampleCmd.QUERY_ORDER_TYPE.getValue()).utf8body(params.toString()).build())) {
            return (SamplePacket) requestQueue.getBizSocket().getPacketFactory().getRequestPacket(new Request.Builder().command(SampleCmd.QUERY_ORDER_TYPE.getValue()).utf8body(params.toString()).build());
        }
        return null;
    }

    @Override
    public Packet processPacket(RequestQueue requestQueue, Packet packet) {
        if (orderTypeHashMap != null && orderListPacket != null && orderListPacket.getContent() != null && orderIdArr != null && orderTypeHashMap.size() == orderIdArr.length) {
            JSONObject obj = null;
            try {
                obj = new JSONObject(orderListPacket.getContent());
            } catch (JSONException e) {
                e.fillInStackTrace();
            }catch (Exception e){
                e.fillInStackTrace();
            }
            try {
                if (obj != null) {
                    JSONArray resultArr = obj.optJSONArray("result");
                    if (resultArr != null) {
                        for (int i = 0; i < resultArr.length(); i++) {
                            JSONObject order = resultArr.optJSONObject(i);
                            if (order != null) {
                                int orderId = order.optInt("orderId");

                                JSONObject orderType = null;
                                try {
                                    if (orderTypeHashMap.get(orderId) != null && ((SamplePacket) orderTypeHashMap.get(orderId)).getContent() != null) {
                                        orderType = new JSONObject(((SamplePacket) orderTypeHashMap.get(orderId)).getContent());
                                        if (orderType != null) {

                                            order.put("orderType", orderType.optInt("ordertype", 0));
                                            order.put("orderTypeRes", orderType);
                                        }
                                    }
                                } catch (JSONException e) {
                                    e.fillInStackTrace();
                                }
                            }
                        }
                    }
                }
                SamplePacket samplePacket = (SamplePacket) packet;
                samplePacket.setCommand(orderListPacket.getCommand());
                samplePacket.setContent(obj== null ?"" : obj.toString());
                LoggerUtil.i("合并订单列表和类型: " + samplePacket.getContent());
                return samplePacket;

            } catch (Exception e) {
                e.fillInStackTrace();
            }
        }
        return null;
    }
}
